package tcu.yuyp.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import tcu.yuyp.pojo.R;
import tcu.yuyp.pojo.User;
import tcu.yuyp.service.impl.LoginService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//用户登录
@WebServlet("/travel/login")
public class LoginServlet extends HttpServlet {
    List<User> userList = new ArrayList<>();
    private final LoginService loginService;

    //通过构造器注入的方式实现注入
    public LoginServlet(LoginService loginService){
        this.loginService = loginService;
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //设置响应的数据格式和字符编码
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");


        ObjectMapper mapper = new ObjectMapper();
        var r = new R();

        //获取登录的请求体数据
        User loginUser = mapper.readValue(req.getReader(), User.class);

        //调用service层的方法进行登录的判断
        loginService.postLoginResponse(userList,loginUser,r);

        if (r.getCode() == 200){
            //登录成功
            HttpSession session = req.getSession();//获取session对象
            session.setAttribute("loginName",loginUser.getName());//将登录成功的用户放到session域中
        }

        //响应数据
        resp.getWriter().write(mapper.writeValueAsString(r));
    }
}
